package rst

import (
	"encoding/json"
	"fmt"
)

const (
	success = 200
	fail    = 400
)

type Rst struct {
	rst map[string]any
}

func New() *Rst {
	return &Rst{make(map[string]any)}
}

func (r *Rst) SetMsg(msg string) *Rst {
	r.rst["msg"] = msg
	return r
}
func (r *Rst) SetCode(code int) *Rst {
	r.rst["code"] = code
	return r
}
func (r *Rst) SetData(data any) *Rst {
	r.rst["data"] = data
	return r
}
func (r *Rst) Success(msg string) *Rst {
	r.SetMsg(msg)
	return r
}
func (r *Rst) Fail(msg string) *Rst {
	r.SetCode(fail)
	r.SetMsg(msg)
	return r
}
func (r *Rst) Data(data any) *Rst {
	jsonData, _ := json.Marshal(data)
	r.SetData(jsonData)
	return r
}

func (rst Rst) String() string {
	if rst.rst["code"] == nil {
		rst.rst["code"] = success
	}
	if rst.rst["msg"] == nil {
		rst.rst["msg"] = ""
	}
	if rst.rst["data"] == nil {
		rst.rst["data"] = struct {
		}{}
	}
	return fmt.Sprintf("{\"code\":%d,\"msg\":\"%s\",\"data\":%s}", rst.rst["code"], rst.rst["msg"], rst.rst["data"])
}
